package captcha;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class Captcha {

    private static String code;
    private static final char[] SYMBOLS = {'1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','J','K','L','M','N','P','R','S','T','U','Y','X'};
    private static final Color[] BACKGROUND_COLORS = {Color.CYAN, Color.MAGENTA, Color.PINK, Color.YELLOW};
    
    private static final Font f1 = new Font("SansSerif", Font.BOLD, 17);
    private static final Font f2 = new Font("SansSerif", Font.BOLD + Font.ITALIC, 17);
    private static final Font f3 = new Font("SansSerif", Font.BOLD, 20);
    private static final Font f4 = new Font("SansSerif", Font.BOLD + Font.ITALIC, 20);
    private static final Font f5 = new Font("SansSerif", Font.BOLD, 23);
    private static final Font f6 = new Font("SansSerif", Font.BOLD + Font.ITALIC, 23);
    private static final Font[] FONTS = {f1,f2,f3,f4,f5,f6};

    public static void drawCaptcha(Graphics2D g, HttpServletRequest request){
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        code = "";
        Random ran = new Random();
        char[] tempCode = new char[6];

        for (int i = 0; i < tempCode.length; i++) {
            tempCode[i] = SYMBOLS[ran.nextInt(29)];
            code += tempCode[i];
        }

        g.setColor(Color.WHITE);
        g.fillRect(0, 0, 200, 50);
        int rotation = 0;
        for (int i = 0; i < 50; i++) {
            g.setColor(BACKGROUND_COLORS[ran.nextInt(4)]);
            rotation = ran.nextInt(45);
            g.rotate(rotation);
            int size = ran.nextInt(25)+5;
            g.fillRect(ran.nextInt(200), ran.nextInt(25), size, size);
            g.fillOval(ran.nextInt(200), ran.nextInt(25), size, size);

            g.rotate(-rotation);
        }
        
        BufferedImage codeImage = new BufferedImage(150, 30, BufferedImage.BITMASK);
        Graphics2D codeG = codeImage.createGraphics();
        
        codeG.setColor(Color.BLACK);
        
        
        
        
        
        for (int i = 0; i < tempCode.length; i++) {
            codeG.setFont(FONTS[ran.nextInt(6)]);
            codeG.drawChars(tempCode, i, 1, i * 20, 25);
            
        }
        
        codeG.dispose();
        
        g.drawImage(codeImage, ran.nextInt(90), ran.nextInt(35) - 8, 150, 30, null);

        g.setColor(Color.BLACK);        
        
         for (int i = 0; i < 5; i++) {
            g.drawLine(0, ran.nextInt(50), 200, ran.nextInt(50));

            
        }
         HttpSession session = request.getSession();
         
         session.setAttribute("CAPTCHA_CODE", code);
         
    }

    public static String getCode(){
        return code;
    }
}
